package cn.edu.qzit.linpq.service;

import cn.edu.qzit.linpq.base.service.BaseService;
import cn.edu.qzit.linpq.dao.StudentMapper;
import cn.edu.qzit.linpq.dao.StudentRepository;
import cn.edu.qzit.linpq.entity.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ClassName : cn.edu.qzit.linpq.service.StudentService
 * Desc : Service 用来编写业务的代码层
 *
 * @author : LINPQ
 * @date : 2022/6/16 14:41
 */
@Service
@Slf4j
public class StudentService extends BaseService<Student, StudentMapper> {

    @Autowired
    StudentMapper studentMapper;
    @Autowired
    StudentRepository studentRepository;


    @Cacheable(value = "user", key = "#id")
    public Student get(Integer id) {
        Student student = studentMapper.findById(id);
        log.info("[查询学生信息Service]：{}", student);
        return student;
    }

    /**
     * CachePut注解需要跟Cacheable注解的方法拥有相同的返回值，否则失效
     *
     * @param student
     * @return
     */
    @CachePut(value = "user", key = "#student.id")
    public Student saveCache(Student student) {
        if (student.getId() != null) {
            studentMapper.update(student);
        } else {
            studentMapper.save(student);
        }
        log.info("[保存学生信息Service]：{}", student);
        return studentMapper.findById(student.getId());
    }

    @CacheEvict(value = "user", key = "#id")
    public void deleteCache(Integer id) {
        studentMapper.delete(id);
        log.info("[删除学生信息Service]：{}", id);
    }

}
